<template>
  <div>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="searchFrom" class="search-form">
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleEdit()"
          >添加</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      v-loading="$store.state.loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="name" label="名称" width="250">
      </el-table-column>
      <el-table-column sortable prop="desc" label="说明" width="300">
      </el-table-column>
      <el-table-column sortable prop="createAt" label="添加时间" width="150">
        <template slot-scope="scope">
          <div>{{ scope.row.createAt | timestampToTime }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="100">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            @click="handleEditScript(scope.$index, scope.row)"
            >编辑转换脚本</el-button
          >
          <el-popconfirm
            title="确认要删除？"
            @confirm="handleDelete(scope.$index, scope.row)"
            class="mg-left-10"
          >
            <el-button slot="reference" size="mini" type="danger" plain
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      v-bind:data="searchFrom"
      @onPagePaging="onPagePaging"
    ></Pagination>

    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="40%"
      @click="closeDialog"
    >
      <el-form
        label-width="120px"
        :model="editForm"
        :rules="rules"
        ref="editForm"
      >
        <el-form-item label="转换器名称" prop="name">
          <el-input
            size="small"
            v-model="editForm.name"
            auto-complete="off"
            placeholder="请输入转换器名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="说明" prop="desc">
          <el-input
            size="small"
            v-model="editForm.desc"
            auto-complete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="$store.state.loading"
          class="title"
          @click="submitEditForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="转换脚本编写"
      :visible.sync="editScriptVisible"
      width="80%"
      @click="closeDialog"
    >
      <el-row>
        <el-col :span="16">
          转换脚本：
          <div>new (function () {</div>
          <ScriptEditor :code="editScript"></ScriptEditor>
          <div>})()</div>
        </el-col>
        <el-col :span="1">&nbsp;</el-col>
        <el-col :span="7">
          测试数据：
          <div style="height: 200px; overflow: auto">
            <JsonEditor :code="testDataScript"></JsonEditor>
          </div>
          <el-row style="padding: 5px 5px">
            <el-col :span="10"> 测试结果： </el-col>
            <el-col :span="7">
              <el-button size="mini" type="primary" @click="execDecodeTest"
                >解码测试</el-button
              >
            </el-col>
            <el-col :span="7">
              <el-button size="mini" type="primary" @click="execEncodeTest"
                >编码测试</el-button
              >
            </el-col>
          </el-row>
          <div>
            <el-input
              type="textarea"
              v-model="testResult"
              :readonly="true"
              :rows="7"
            >
            </el-input>
          </div>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="$store.state.loading"
          @click="submitSaveScript"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  ConverterList,
  ConverterAdd,
  ConverterSave,
  ConverterDelete,
  ConverterScriptSave,
  ConverterScriptGet,
} from "@/api/protocolApi";
import Pagination from "../../components/Pagination";
import ScriptEditor from "../../components/ScriptEditor.vue";
import JsonEditor from "./JsonEditor.vue";

export default {
  data() {
    var validateId = (rule, value, callback) => {
      console.log(new RegExp("^[\\-\\_a-z0-9]+$", "i").test(value));
      if (!new RegExp("^[\\-\\_a-z0-9]+$", "i").test(value)) {
        callback(new Error("id只能是数字、字母、-和_的组合"));
      } else {
        callback();
      }
    };

    return {
      loading: false,
      editFormVisible: false,
      editScriptVisible: false,
      isAdd: true,
      title: "",
      editForm: {
        id: "",
        name: "",
        desc: "",
      },
      rules: {
        id: [
          { required: true, message: "请输入网关ID", trigger: "blur" },
          { validator: validateId, trigger: "blur" },
        ],
      },
      searchFrom: {
        page: 1,
        size: 10,
        total: 0,
      },
      listData: [],
      editScript: {},
      testDataScript: {
        script: "{}",
      },
      testResult: "",
    };
  },
  components: {
    Pagination,
    ScriptEditor,
    JsonEditor,
  },
  created() {
    this.getdata(this.searchFrom);
  },
  methods: {
    getdata(parameter) {
      ConverterList(parameter).then((res) => {
        this.listData = res.data;
        this.searchFrom.total = res.total;
      });
    },
    search() {
      this.getdata(this.searchFrom);
    },
    onPagePaging() {
      this.search();
    },
    handleEdit(index, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.isAdd = false;
        this.title = "修改转换器";
        this.editForm.id = row.id;
        this.editForm.name = row.name;
        this.editForm.desc = row.desc;
      } else {
        this.isAdd = true;
        this.title = "添加转换器";
        this.editForm.id = "";
        this.editForm.name = "";
        this.editForm.desc = "";
      }
    },
    handleEditScript(idx, row) {
      let load = this.$loading();
      ConverterScriptGet(row.id).then((res) => {
        this.editScriptVisible = true;
        this.editScript.id = row.id;
        if (!res) {
          res = `this.decode = function (msg) {
  return null;
};
this.encode = function (service,device) {
  return null;
}`;
        }
        this.editScript = { id: row.id, script: res };
        this.testDataScript.script =
          localStorage.getItem("testDataScript2_" + row.id) || "{}";
        load.close();
      });
    },
    handleDelete(idx, row) {
      ConverterDelete(row.id).then(() => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
        });
        this.search();
      });
    },
    submitEditForm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            ConverterAdd(this.editForm).then(() => {
              this.$notify({
                title: "成功",
                message: "添加成功",
                type: "success",
              });
              this.editFormVisible = false;
              this.search();
            });
          } else {
            ConverterSave(this.editForm).then(() => {
              this.$notify({
                title: "成功",
                message: "修改成功",
                type: "success",
              });
              this.editFormVisible = false;
              this.search();
            });
          }
        }
      });
    },
    submitSaveScript() {
      ConverterScriptSave(this.editScript).then(() => {
        this.$notify({
          title: "成功",
          message: "修改成功",
          type: "success",
        });
        this.editScriptVisible = false;
        this.search();
      });
    },
    closeDialog() {
      this.editFormVisible = false;
      this.editScriptVisible = false;
    },
    execDecodeTest() {
      try {
        localStorage.setItem(
          "testDataScript2_" + this.editScript.id,
          this.testDataScript.script || "{}"
        );

        var script = "new (function (){" + this.editScript.script + "})()";
        var coder = eval(script);
        var testData = eval(
          "(function(){return " + this.testDataScript.script + "})()"
        );
        this.testResult = JSON.stringify(coder.decode(testData));
      } catch (err) {
        this.testResult = err;
      }
    },
    execEncodeTest() {
      try {
        localStorage.setItem(
          "testDataScript2_" + this.editScript.id,
          this.testDataScript.script || "{}"
        );

        var script = "new (function (){" + this.editScript.script + "})()";
        var coder = eval(script);
        var testData = eval(
          "(function(){return " + this.testDataScript.script + "})()"
        );
        this.testResult = JSON.stringify(coder.encode(testData));
      } catch (err) {
        this.testResult = err;
      }
      console.log(this.testResult);
    },
  },
};
</script>
